package com.century.sjt.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.activity.order.MyOrderActivity;
import com.century.sjt.activity.order.MyOrderDetailsActivity;
import com.century.sjt.entity.MyOrder;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.svpprogresshud.SVProgressHUD;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:周玲波
 * @Description: 我的订单适配器
 * @date : 2016/8/29 20:33
 */
public class MyOrderAdapter extends BaseAdapter {
    Context mContext;
    List<MyOrder> mList;
    LayoutInflater inflater;
    private SVProgressHUD mSVProgressHUD;
    Handler mHandler;

    public MyOrderAdapter(Context mContext, List<MyOrder> mList, Handler mHandler) {
        this.mContext = mContext;
        this.mList = mList;
        this.mHandler = mHandler;
        inflater = LayoutInflater.from(mContext);
        mSVProgressHUD = new SVProgressHUD(mContext);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.sjt_myorder_lv_item, null);
            holder.tv_order_time = (TextView) convertView.findViewById(R.id.tv_order_time);
            holder.iv_goods_icon = (ImageView) convertView.findViewById(R.id.iv_goods_icon);
            holder.order_shopname = (TextView) convertView.findViewById(R.id.order_shopname);
            holder.tv_order_total = (TextView) convertView.findViewById(R.id.tv_order_total);
            holder.btn_order_cancle = (Button) convertView.findViewById(R.id.btn_order_cancle);
            holder.btn_order_sure = (Button) convertView.findViewById(R.id.btn_order_sure);
            holder.ll_order_detail = (LinearLayout) convertView.findViewById(R.id.ll_order_detail);
            holder.ll_oreder = (LinearLayout) convertView.findViewById(R.id.ll_oreder);
            holder.tv_order_status = (TextView) convertView.findViewById(R.id.tv_order_status);
            holder.tv_order_currency= (TextView) convertView.findViewById(R.id.tv_order_currency);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tv_order_time.setText(mList.get(position).getDate());
        holder.order_shopname.setText(mList.get(position).getShopName());
        holder.tv_order_total.setText(mList.get(position).getOrderAmount());
        holder.tv_order_currency.setText(mList.get(position).getOrderCurrency());
        Glide.with(mContext).load(mList.get(position).getShopLogo()).into(holder.iv_goods_icon);
        statusJudge(mList.get(position).getStatus(), holder,position);
        holder.ll_order_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MyOrderDetailsActivity.class);
                intent.putExtra("orderId", mList.get(position).getOrderId());
                intent.putExtra("falg", 2);
                mContext.startActivity(intent);
            }
        });
        holder.btn_order_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去支付
                if (mList.get(position).getStatus().equals("1")) {
                    Intent intent = new Intent(mContext, MyOrderDetailsActivity.class);
                    intent.putExtra("orderId", mList.get(position).getOrderId());
                    intent.putExtra("falg", 2);
                    mContext.startActivity(intent);
                } else if (mList.get(position).getStatus().equals("2")) {
                    //申请退款
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle(mContext.getResources().getString(R.string.text_prompt));
                    builder.setMessage(mContext.getResources().getString(R.string.text_sure_refund));
                    builder.setPositiveButton(mContext.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            mSVProgressHUD.showWithStatus(mContext.getResources().getString(R.string.text_apply_refund));
                            requestRefund(mList.get(position).getOrderId());
                        }
                    });
                    builder.setNegativeButton(mContext.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setCancelable(false);
                    builder.create().show();
                }
            }
        });

        //取消订单
        holder.btn_order_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle(mContext.getResources().getString(R.string.text_prompt));
                builder.setMessage(mContext.getResources().getString(R.string.text_sure_cancle_order));
                builder.setPositiveButton(mContext.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        cancleOrder(mList.get(position).getOrderId());
                    }
                });
                builder.setNegativeButton(mContext.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                builder.create().show();
            }
        });
        return convertView;
    }

    /**
     * @Description: 状态判断
     * @author: 周玲波
     * @date: 2016/9/10 20:04
     */
    private void statusJudge(String status, ViewHolder holder,int position) {
        switch (status) {
            case "1":
                holder.btn_order_cancle.setVisibility(View.VISIBLE);
                holder.btn_order_sure.setVisibility(View.VISIBLE);
                holder.btn_order_sure.setBackgroundResource(R.drawable.btn_submit);
                holder.ll_oreder.setVisibility(View.VISIBLE);
                holder.tv_order_status.setVisibility(View.GONE);
                break;
            case "2":
                //避掉
                holder.ll_oreder.setVisibility(View.VISIBLE);
                holder.btn_order_cancle.setVisibility(View.INVISIBLE);
                holder.btn_order_sure.setVisibility(View.VISIBLE);
                holder.btn_order_sure.setBackgroundResource(R.drawable.btn_submit_white);
                holder.btn_order_sure.setText(mContext.getResources().getString(R.string.btn_in_refund));
                holder.btn_order_sure.setTextColor(mContext.getResources().getColor(R.color.textdefault_textgrey));
                holder.tv_order_status.setVisibility(View.GONE);
              //退款退后删除
//                holder.ll_oreder.setVisibility(View.GONE);
//                holder.tv_order_status.setVisibility(View.VISIBLE);
//                holder.tv_order_status.setText(mContext.getResources().getString(R.string.text_already_pay));

                break;
            case "4":
                holder.ll_oreder.setVisibility(View.GONE);
                holder.tv_order_status.setVisibility(View.VISIBLE);
                holder.tv_order_status.setText(mList.get(position).getStatusName());
                break;
            case "8":
                holder.ll_oreder.setVisibility(View.GONE);
                holder.tv_order_status.setVisibility(View.VISIBLE);
                holder.tv_order_status.setText(mList.get(position).getStatusName());
                break;
            default:
                if (status.equals("3") | status.equals("5") | status.equals("6") | status.equals("7")) {
                    holder.ll_oreder.setVisibility(View.GONE);
                    holder.tv_order_status.setVisibility(View.GONE);
                }
                switch(status){
                    case "3":
                        //避掉
//                        holder.ll_oreder.setVisibility(View.VISIBLE);
//                        holder.btn_order_cancle.setVisibility(View.INVISIBLE);
//                        holder.btn_order_sure.setVisibility(View.VISIBLE);
//                        holder.btn_order_sure.setBackgroundResource(R.drawable.btn_submit_white);
//                        holder.btn_order_sure.setText(mContext.getResources().getString(R.string.btn_apply_goods_rejected));
//                        holder.btn_order_sure.setTextColor(mContext.getResources().getColor(R.color.textdefault_textgrey));
                        //退款退后删除
                        holder.ll_oreder.setVisibility(View.GONE);
                        holder.tv_order_status.setVisibility(View.VISIBLE);
                        holder.tv_order_status.setText(mList.get(position).getStatusName());

                        break;
                    case "5":
                        holder.ll_oreder.setVisibility(View.GONE);
                        holder.tv_order_status.setVisibility(View.VISIBLE);
                        holder.tv_order_status.setText(mList.get(position).getStatusName());
                        break;
                    case "6":
                        holder.ll_oreder.setVisibility(View.GONE);
                        holder.tv_order_status.setVisibility(View.VISIBLE);
                        holder.tv_order_status.setText(mList.get(position).getStatusName());
                        break;
                    case "7":
                        holder.ll_oreder.setVisibility(View.GONE);
                        holder.tv_order_status.setVisibility(View.VISIBLE);
                        holder.tv_order_status.setText(mList.get(position).getStatusName());
                        break;
                }
                break;


        }
    }

    class ViewHolder {
        TextView tv_order_time;
        TextView order_shopname;
        TextView tv_order_total;
        TextView tv_order_status;
        TextView tv_order_currency;
        ImageView iv_goods_icon;
        Button btn_order_cancle;
        Button btn_order_sure;
        LinearLayout ll_order_detail;
        LinearLayout ll_oreder;
    }

    /**
     * @Description: 申请退款
     * @author: 周玲波
     * @date: 2016/9/10 22:18
     */
    private void requestRefund(final String orderId) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.orderRefund, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        mSVProgressHUD.dismiss();
                        TipUtil.showToast(mContext.getResources().getString(R.string.text_apply_success), mContext, 1);
                    } else {
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", orderId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        ((MyOrderActivity) mContext).mQueue.add(stringRequest);
    }

    /**
     * @Description: 取消订单
     * @author: 周玲波
     * @date: 2016/8/31 10:33
     */
    private void cancleOrder(final String orderId) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.cancleOrder, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {

                        TipUtil.showToast(mContext.getResources().getString(R.string.text_cancle_success), mContext, 1);
                        notifyDataSetChanged();
                    } else {
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", orderId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };


        ((MyOrderActivity) mContext).mQueue.add(stringRequest);
    }


}